import 'package:get/get.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_polling_timer_helper.dart';

import '../../../../service/global_service.dart';
import '../../../../service/realtime_data_server/vehicle_realtime_data/vehicle_battery_info.dart';
import '../../../mixin/vehicle_type_mixin.dart';
import '../../../models/battery_pack_model.dart';
import '../../../models/settting_item_model.dart';
import 'state.dart';

// 电池信息控制器
class BatteryInfoController extends GetxController with RealtimeInfoMixin {
  // 状态
  final BatteryInfoState state = BatteryInfoState();

  // 当前车辆类型
  VehicleType get _vehicleType => GlobalService.to.currentVehicleType;

  @override
  void onInit() {
    super.onInit();

    state.itemList.value = _vehicleType.getVehicleBMSCellList();

    Future.delayed(const Duration(milliseconds: 300), () {
      // 初始化BMS数据监听
      _refreshBMSData();
    });
  }

  // 初始化BMS数据监听
  _refreshBMSData() {
    // 延迟300毫秒，确保页面渲染完成后再监听变化
    return realtimeInfoMixinStopLoopToGetVehicleRealTimeData().then(
      (_) => realtimeInfoMixinStartLoopToGetVehicleRealTimeData(
        pollingTypes:
            RealtimeDataPollingTimeHelper.vehicleBatteryInfoPagePollingTypes,
        batteryInfoCallback: (p0) {
          _refreshSettingItems(p0);
        },
      ),
    );
  }

  // 刷新设置项
  void _refreshSettingItems(VehicleBatteryInfo info) {
    // 电池包列表
    List<BatteryPackModel> batteryPackModels = info.batteryPacks;
    void setValue(SettingRowModel rowItem) {
      if (rowItem.title == local.bms_sn) {
        rowItem.value = "";
      } else if (rowItem.title == local.bms_charging_status) {
        rowItem.value = batteryPackModels
            .map((e) => e.stateCharge ? "ON" : "OFF")
            .join("\n");
      } else if (rowItem.title == local.voltage) {
        rowItem.value = batteryPackModels
            .map((e) => "${(e.voltage / 100).toStringAsFixed(1)}V")
            .join("\n");
      } else if (rowItem.title == local.bms_charging_current) {
        rowItem.value = batteryPackModels
            .map((e) => "${(e.chargeCurrent / 100).toStringAsFixed(1)}A")
            .join("\n");
      } else if (rowItem.title == local.bms_charging_mos) {
        rowItem.value = batteryPackModels
            .map((e) => e.stateCharge ? "ON" : "OFF")
            .join("\n");
      } else if (rowItem.title == local.bms_fault_status) {
        rowItem.value = batteryPackModels
            .map((e) => e.batteryError ? "🔴" : "🟢")
            .join("   ");
      } else if (rowItem.title == local.bms_warning_status) {
        rowItem.value = batteryPackModels
            .map((e) => e.batteryWarning ? "🔴" : "🟢")
            .join("   ");
      } else if (rowItem.title == local.bms_protection_status) {
        rowItem.value = batteryPackModels
            .map((e) => e.batteryProtect ? "🔴" : "🟢")
            .join("   ");
      }
    }

    // 优化：使用递归方式遍历所有子项，减少嵌套循环
    void updateItems(List<SettingRowModel> items) {
      for (var rowItem in items) {
        setValue(rowItem);
        if (rowItem.subItems.isNotEmpty) {
          updateItems(rowItem.subItems);
        }
      }
    }

    for (var item in state.itemList) {
      updateItems(item.subItems);
    }
    state.itemList.refresh();
  }
}
